import react, { useEffect, useRef, useState } from 'react';
import Draggable from 'react-draggable';
import axios from 'axios';

const CanvasBox = () => {
  const canvasRef = useRef(null);
  const inputRef = useRef(null);
  const [imgList, setimgList] = useState([]);
  const [id, setId] = useState([1]);
  const [event, setEvent] = useState();
  const [x_y, setX_y] = useState([]);

  //初始化画布背景颜色，背景颜色为灰色
  useEffect(() => {
    var canvas = canvasRef.current;
    var c = canvas.getContext('2d');
    c.fillStyle = "#F2F3F5";
    c.fillRect(0, 0, canvas.width, canvas.height);
  })
  //点击保存，保存画布当前像素成图片，并将图片存入数据库
  const save = () => {
    var cvs = canvasRef.current;
    var c = cvs.getContext('2d');
    console.log(imgList);
    imgList.forEach(e => {
      var img = new Image();
      img.setAttribute("crossOrigin", 'anonymous')
      img.src = e.src;
      img.onload = function () {
        c.drawImage(img, e.x, e.y, e.width, e.height);
      }
    });
    setTimeout(() => {
      const url = cvs.toDataURL();
      var arr = url.split(',');
      console.log(url);
      axios.post('http://192.168.72.166:8080/api/postUrl', {
        "url": arr[1]
      }).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err);
      })
    }, 1000);
  }
  //鼠标松开后，获取图片当前位置信息并存入imgList，并创建新图片dom节点并放入页面
  document.onmouseup = (e) => {
    var cvs = canvasRef.current;
    var cvsX = getLeft(cvs);
    var cvsY = getTop(cvs);
    if (e.target.tagName == 'IMG') {
      // console.log(e.target.tagName);
      // console.log(e.target.style.transform);
      var num3 = e.target.style.transform.match(/[-|\d]+(\.\d+)?/g);
      var x = getLeft(e.target) + parseInt(num3[0]) - cvsX;
      var y = getTop(e.target) + parseInt(num3[1]) - cvsY;
      imgList.forEach((ele, index) => {
        if (e.target.src == ele.src) {
          var newList = imgList;
          newList.splice(index, 1);
          setimgList(newList);
        }
      });
      setimgList((pre) => {
        const item = {
          // id:id,
          src: e.target.src,
          width: e.target.width,
          height: e.target.height,
          x: x,
          y: y
        };
        pre.push(item);
        return [...pre]
      })
      console.log(imgList);

      if (id.some(ele => ele == e.target.src) == false) {
        setId((items) => {
          items.push(e.target.src);
          return [...items];
        });
        createDom(e);
      }
    }
  }
  //选中要放大或者缩小的图片
  document.onmousedown = (e) => {
    if (e.target.tagName == 'IMG') {
      setEvent(e.target);
    }
  }
  //放大图片
  const imgToSizeAdd = () => {
    console.log(event)
    event.width = event.width * (1 + 0.1);
    event.height = event.height * (1 + 0.1);
    imgList.forEach((ele, index) => {
      if (event.src == ele.src) {
        setX_y([ele.x, ele.y]);
        var newList = imgList;
        newList.splice(index, 1);
        setimgList(newList);
      }
    });
    setimgList((pre) => {
      const item = {
        src: event.src,
        width: event.width,
        height: event.height,
        x: x_y[0],
        y: x_y[1]
      };
      pre.push(item);
      return [...pre]
    })
  }
  //缩小图片
  const imgToSizeMinus = () => {
    console.log(event)
    const oldWidth = event.width;
    const oldHeight = event.height;
    event.width = event.width * (1 - 0.1);
    event.height = event.height * (1 - 0.1);
    imgList.forEach((ele, index) => {
      if (event.src == ele.src) {
        setX_y([ele.x, ele.y]);
        var newList = imgList;
        newList.splice(index, 1);
        setimgList(newList);
      }
    });
    setimgList((pre) => {
      const item = {
        src: event.src,
        width: event.width,
        height: event.height,
        x: x_y[0] + oldWidth - event.width,
        y: x_y[1] + oldHeight - event.height
      };
      pre.push(item);
      return [...pre]
    })
  }
  //移动图片后，新建图片节点
  const createDom = (e) => {
    let newDom = document.createElement("img");
    newDom.src = e.target.src;
    newDom.width = e.target.width;
    newDom.height = e.target.height;
    newDom.style.position = 'absolute';
    const top = getTop(e.target);
    const left = getLeft(e.target);
    newDom.style.top = '' + top + 'px';
    newDom.style.left = '' + left + 'px';
    newDom.style.zIndex = '100';
    // newDom.style.transform = 'translate(-'+e.target.width+'px,0px)';
    // newDom.style.transform = 'translate(0px,-'+ e.target.height+')';
    // newDom.style.transform = 'translate(-'+e.target.width+'px,-'+ e.target.height+'px)';
    // console.log(e.target.parentNode);
    e.target.parentNode.appendChild(newDom);

  }
  //获取dom元素据页面上方的距离，递归
  const getTop = (e) => {  // e:dom元素
    var offset = e.offsetTop;
    if (e.offsetParent != null) offset += getTop(e.offsetParent);
    return offset;
  }
  //获取dom元素据页面左方的距离，递归
  const getLeft = (e) => {  // e:dom元素
    var offset = e.offsetLeft;
    if (e.offsetParent != null) offset += getLeft(e.offsetParent);
    return offset;
  }
  //在input框中输入值，点击确定后改变画布的颜色，例：ccff00
  const changeColor = () => {
    var input = inputRef.current;
    var canvas = canvasRef.current;
    var c = canvas.getContext('2d');
    console.log(input.value);
    var color = '#' + input.value;
    c.fillStyle = color;
    c.fillRect(0, 0, canvas.width, canvas.height);
  }
  return (<div className='cvs'>
    <div width='900' height='450' className='cvs-con'>
      <canvas
        ref={canvasRef}
        width="270"
        height="400"
        style={{ backgroundColor: '#F2F3F5', border: '2px dashed #ccc', marginLeft: '2%', marginTop: '10%' }}
      // 直接将 width 和 height 作为元素属性写上，使用 css 来限定宽高的话，会有其他问题
      >
      </canvas>
    </div>
    <div width='200' height='450' className='cvs-btn'>
      <button onClick={save}>裁剪</button>
      <button onClick={imgToSizeAdd}>放大</button>
      <button onClick={imgToSizeMinus}>缩小</button>
      <input type="text" ref={inputRef}></input><button onClick={changeColor}>确定</button>
    </div>

  </div>)
}
export default CanvasBox;



